<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
// import { useRoute } from 'vue-router'
// import router from '@/router'
// const route = useRoute()
const isLoading = ref(false)
const userStore = useUserStore()
const form = ref({ phone: '18201288771', password: '111111' })
const onSubmit = async () => {
  // 表单校验
  await formRef.value?.validate().catch((err) => {
    ElMessage.error('表单校验失败！')
    // 抛出错误 中断程序执行
    throw err
  })
  // 校验成功后
  isLoading.value = true
  await userStore
    .userLogin(form.value)
    // 让登录中直接跳转
    // .then(() => {
    // router.push((route.query.redirect as string) || '/')
    // })
    .finally(() => {
      isLoading.value = false
    })
}
// 定义表单校验规则
const rules = reactive<FormRules>({
  phone: [
    { required: true, message: '电话号码不能空', trigger: 'blur' },

    // 正则校验手机号码
    { pattern: /^1\d{10}$/, message: '电话号码需为1开头的10位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度需为6-18位', trigger: 'blur' }
  ]
})
const formRef = ref<FormInstance>()
</script>
<template>
  <div class="login">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="top" size="large">
      <h2>用户登录</h2>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>

      <el-form-item>
        <!-- loading 避免重复登录 -->
        <el-button type="primary" @click="onSubmit" :loading="isLoading">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped lang="scss">
.login {
  // background-color: #e9e9eb;
  background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);
  height: 98vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-form {
    width: 300px;
    // height: 300px;
    background-color: #fff;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 4px 10px gray;

    h2 {
      margin: 0px 70px;
    }

    .el-form-item {
      margin-top: 20px;
    }

    .el-button {
      width: 100%;
      margin-top: 30px;
    }
  }
}
</style>
